//
//  ECMineProfileViewController.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/16.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECMineProfileViewController.h"
#import "ECMineProfileTypeOneCell.h"
#import "ECMineProfileTypeTwoCell.h"
#import "ECMineProfileSelfIntroVC.h"
#import "ECMineProfileSelfSignVC.h"
#import "ECProfileSelfTruenameVc.h"
//生日选择类
#import "CYDataHelper.h"
#import "MNDatePickerView.h"
#import "MNPickerView.h"
//相册选择类
#import <MobileCoreServices/MobileCoreServices.h>
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "STConfig.h"


@interface ECMineProfileViewController ()<UITableViewDelegate,UITableViewDataSource,MNDatePickerViewDelegate,MNPickerViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, STPhotoKitDelegate>

@property (nonatomic, strong) UITableView *tableView;
///数据源数据
@property (nonatomic, strong) NSMutableArray *dataArray;
///生日pick
@property(nonatomic,strong)MNDatePickerView *birPicker;
///性别pick
@property(nonatomic,strong)MNPickerView *sexPicker;
///性别选择数组
@property (nonatomic, strong) NSMutableArray *sexArray;

@end

@implementation ECMineProfileViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDataWithURL];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的资料";
    [self.view addSubview:self.tableView];
    [self addSubviews];
}

-(void)addSubviews{//添加选择器
    
    _sexArray = [NSMutableArray array];
    [_sexArray addObject:@"男"];
    [_sexArray addObject:@"女"];
    
}

-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_Me
                           params:nil
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              
                              dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                  // 处理耗时操作的代码块...
                                  NSString *smallAvatar = json[@"data"][@"smallAvatar"];
                                  [UserInfoManager configInfo:@{@"smallAvatar":smallAvatar}];//头像
                                  if ([CYDataHelper isNull:smallAvatar]) {
                                      smallAvatar = @"placehold";
                                  }
                                  [self.dataArray[0][0] replaceObjectAtIndex:1 withObject:smallAvatar];//头像
                                  
                                  NSString *truename = json[@"data"][@"truename"];

                                  [self.dataArray[0][1] replaceObjectAtIndex:1 withObject:truename];//真实姓名
                                  
                                  [self.dataArray[0][2] replaceObjectAtIndex:1 withObject:json[@"data"][@"gender"]];//性别
                                  
                                  NSString *birthday = json[@"data"][@"birthday"];
                                  if ([CYDataHelper isNull:birthday]) {
                                      birthday = @"2018-01-01";
                                  }
                                  [self.dataArray[0][3] replaceObjectAtIndex:1 withObject:birthday];//生日
                                  
                                  NSString *signature = json[@"data"][@"signature"];

                                  [self.dataArray[1] replaceObjectAtIndex:1 withObject:signature];//个签
                                  
                                  NSString *intro = json[@"data"][@"intro"];

                                  [self.dataArray[2] replaceObjectAtIndex:1 withObject:intro];//自我介绍
                                  
                                  int tmpSex;
                                  if ([self.dataArray[0][2][1] isEqualToString:@"male"]) {
                                      tmpSex = 0;
                                  }else{
                                      tmpSex = 1;
                                  }
                                  
                                  NSString *birthdayStr = self.dataArray[0][3][1];
                                  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                                  [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                                  NSDate *birthdayDate = [dateFormatter dateFromString:birthdayStr];
                                  
                                  //通知主线程刷新
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      //回调或者说是通知主线程刷新，
                                      
                                      [self.tableView reloadData];
                                      
                                      _sexPicker = [[MNPickerView alloc] initWithDataArray:_sexArray defaultSelecte:tmpSex];
                                      _sexPicker.delegate = self;
                                      
                                      _birPicker = [[MNDatePickerView alloc] initWithDate:birthdayDate];
                                      _birPicker.delegate = self;
                                      _birPicker.pickerTag = 0;
                                  });
                                  
                              });
                          }
                          failure:^(NSError *error) {
                              DLog(@"%@",error);
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                              }
                          }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else{
        return 1;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        NSString *indetify = @"ECMineProfileTypeOneCell";
        ECMineProfileTypeOneCell *cell = [tableView dequeueReusableCellWithIdentifier:indetify];
        if (!cell) {
            cell = [[ECMineProfileTypeOneCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indetify];
        }
        //设置数据
        [cell setContentWithData:self.dataArray andIndexPath:indexPath];
        return cell;
    }else{
        NSString *indetify = @"ECMineProfileTypeTwoCell";
        ECMineProfileTypeTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:indetify];
        if (!cell) {
            cell = [[ECMineProfileTypeTwoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indetify];
        }
        //设置数据
        [cell setContentWithData:self.dataArray andIndexPath:indexPath];
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return kProportion_Height(240);
        }else{
            return kProportion_Height(144);
        }
    }else{
        CGFloat Height = [self getHeightWithStr:self.dataArray[indexPath.section][1]];
        return kProportion_Height(270)+ Height;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.001)];
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kProportion_Height(30))];
    view.backgroundColor = [UIColor colorWithHexString:@"#F5F5F5"];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kProportion_Height(30);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {//个人信息
        switch (indexPath.row) {
            case 0:{//头像选择
                [self editImageSelected];
            }
                break;
            case 1:{//修改真实姓名
                ECProfileSelfTruenameVc *vc = [[ECProfileSelfTruenameVc alloc]init];
                vc.name = self.dataArray[0][1][1];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2:{//性别选择
                 [_sexPicker showPickerView];
            }
                break;
            case 3:{//生日选择
                [_birPicker showPickerView];
            }
                break;
            default:
                break;
        }
    }else if (indexPath.section == 1){//个签
        ECMineProfileSelfSignVC *vc = [[ECMineProfileSelfSignVC alloc]init];
        vc.selfSign = self.dataArray[1][1];
        [self.navigationController pushViewController:vc animated:YES];
    }else{//自我介绍
        ECMineProfileSelfIntroVC *vc = [[ECMineProfileSelfIntroVC alloc]init];
        vc.selfIntro = self.dataArray[2][1];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/*  获得文字高度  */
-(CGFloat)getHeightWithStr:(NSString *)str{
    
    if ([CYDataHelper isNull:str]) {//自我判断"个性签名"."自我介绍"是否为空,为空情况下手动添加"暂无",便于计算高度
        str = @"暂无";
    }
    CGRect rect= [str boundingRectWithSize:CGSizeMake(kProportion_Width(1080-90), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16*kPercentage]} context:nil];
    return rect.size.height;
}

/*  懒加载tableview  */
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, kScreenWidth, kScreenHeight-kNavHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    }
    return _tableView;
}

/*  懒加载数据  */
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
#warning mark 脑子混了 想不出别的想法出来了 2018年01月16日15:27:48
        NSMutableArray *arr00 = [[NSMutableArray alloc]initWithArray:@[@"头像",@""]];
        NSMutableArray *arr01 = [[NSMutableArray alloc]initWithArray:@[@"姓名",@"学缘"]];
        NSMutableArray *arr02 = [[NSMutableArray alloc]initWithArray:@[@"性别",@""]];
        NSMutableArray *arr03 = [[NSMutableArray alloc]initWithArray:@[@"生日",@"暂无"]];
        NSMutableArray *arr10 = [[NSMutableArray alloc]initWithArray:@[@"个性签名",@""]];
        NSMutableArray *arr20 = [[NSMutableArray alloc]initWithArray:@[@"自我介绍",@""]];
        
        _dataArray = [[NSMutableArray alloc]initWithArray:@[@[arr00,arr01,arr02,arr03],arr10,arr20]];
    }
    return _dataArray;
}

/*
 生日选择回调
 */
-(void)MNDatePickerViewSelectedDate:(NSDate *)date tag:(NSInteger)tag{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    if(tag == 0){//修改生日
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        NSString *dateStr = [dateFormatter stringFromDate:date];
        
        if ([dateStr isEqualToString:self.dataArray[0][3][1]]) {//假如选择相同,不作处理
            return;
        }
       
        //传递参数 网络修改对应值(该数组前2字段对应网络请求参数,最后一个对应更新对应cell标志)
        [self getDataWithURLWithInfo:@[@"birthday",dateStr,@"3"]];
    }
}

/*
 性别选择回调
 */
-(void)MNPickerViewdidSelectRow:(NSInteger)row{
    //来回转换性别标识,.................................
    NSString *sex = [self.sexArray[row]isEqualToString:@"男"]?@"male":@"female";
    
    if ([sex isEqualToString:self.dataArray[0][2][1]]) {//假如选择相同,不作处理
        return;
    }
    
    //传递参数 网络修改对应值(该数组前2字段对应网络请求参数,最后一个对应更新对应cell标志)
    [self getDataWithURLWithInfo:@[@"gender",sex,@"2"]];
}

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected{
    
    if (@available(iOS 11.0, *)) {//iOS11 导航偏移问题
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
    }
    
    UIAlertController *alertController = [[UIAlertController alloc]init];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:action0];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        [photoVC setSizeClip:CGSizeMake(kScreenWidth/4*3, kScreenWidth/4*3)];
        [self presentViewController:photoVC animated:YES completion:^{
            
        }];
    }];
}

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage{
    [MBProgressHUD showHUDAddedTo:(UIView*)[UIApplication sharedApplication].delegate.window animated:YES];
    
    // 上传头像
    NSData *data =UIImageJPEGRepresentation(resultImage, 0.1);
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:[[UserInfoManager shareUser]token] forHTTPHeaderField:@"X-AUTH-TOKEN"];//设置请求头
    [session POST:URL_POST_Me_Avatar parameters:@{@"width":@(kScreenWidth/2)} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"avatar_file" fileName:@"头像.jpeg" mimeType:@"image/jpeg"];//封装成文件
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        MJRefreshLog(@"%@",responseObject);
        [MBProgressHUD hideHUD];
        [self.dataArray[0][0] replaceObjectAtIndex:1 withObject:responseObject[@"data"][@"result"]];//头像
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        [UserInfoManager configInfo:@{@"smallAvatar":responseObject[@"data"][@"result"]}];//保存头像到本地
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        MJRefreshLog(@"%@",error);
        [MBProgressHUD hideHUDForView:(UIView*)[UIApplication sharedApplication].delegate.window animated:YES];
        [MBProgressHUD showTipMessageInWindow:@"头像上传失败"];
    }];
}

/*
 更新性别,生日
 */
-(void)getDataWithURLWithInfo:(NSArray *)infoArray{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_MeSetting
                           params:@{@"field":infoArray[0],
                                    @"value":infoArray[1]
                                    }
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              [MBProgressHUD showTipMessageInWindow:@"更新成功"];
                              
                              dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                  // 处理耗时操作的代码块...
                                  
                                  NSIndexPath *indexPath;
                                  
                                  if ([infoArray[0] isEqualToString:@"gender"]) {//性别
                                      [self.dataArray[0][2] replaceObjectAtIndex:1 withObject:infoArray[1]];//性别
                                      indexPath=[NSIndexPath indexPathForRow:[infoArray[2] integerValue] inSection:0];
                                  }else{//生日
                                      [self.dataArray[0][3] replaceObjectAtIndex:1 withObject:infoArray[1]];//性别
                                      indexPath=[NSIndexPath indexPathForRow:[infoArray[2] integerValue] inSection:0];
                                  }
                                  
                                  //通知主线程刷新
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      //回调或者说是通知主线程刷新，
                                      
                                      //更新对应cell
                                      [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                                  });
                                  
                              });
                              
                          }
                          failure:^(NSError *error) {
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:@"更新失败"];
                              }
                          }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
